<template>
  <div class="add-vehicle-application">
    <div class="header">
      <h2>申请用车</h2>
    </div>
    <div class="content">
      <a-form-model ref="form" :model="form" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
        <!-- 申请人 -->
        <a-form-model-item label="申请人" prop="applicant_id">
          <a-tree-select v-model="form.applicant_id" show-search style="width: 100%" treeNodeFilterProp="title"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree1" placeholder="请选择申请人"
            disabled>
          </a-tree-select>
        </a-form-model-item>
        <!-- 申请部门 -->
        <a-form-model-item label="申请部门" prop="department_id">
          <a-select v-model="form.department_id" disabled>
            <a-select-option v-for="item in departmentList" :key="item.department_id" :value="item.department_id">
              {{ item.department_name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 乘车人 -->
        <a-form-model-item label="乘车人" prop="passenger_ids">
          <a-tree-select v-model="form.passenger_ids" show-search style="width: 100%" treeNodeFilterProp="title"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="personListTree1" placeholder="请选择乘车人"
            multiple>
          </a-tree-select>
        </a-form-model-item>
        <!-- 出发日期 -->
        <a-form-model-item label="出发日期" prop="departure_date">
          <a-date-picker v-model="form.departure_date" />
          <a-select style="width:120px;margin-left:20px;" v-model="form.departure_time_period" placeholder="请选择时间">
            <a-select-option value="上午">
              上午
            </a-select-option>
            <a-select-option value="下午">
              下午
            </a-select-option>
            <a-select-option value="晚上">
              晚上
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 返回日期 -->
        <a-form-model-item label="返回日期" prop="return_date">
          <a-date-picker v-model="form.return_date" />
          <a-select style="width:120px;margin-left:20px;" v-model="form.return_time_period" placeholder="请选择时间">
            <a-select-option value="上午">
              上午
            </a-select-option>
            <a-select-option value="下午">
              下午
            </a-select-option>
            <a-select-option value="晚上">
              晚上
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <!-- 目的地 -->
        <a-form-model-item label="目的地" prop="destination">
          <a-cascader :options="area" v-model="form.destination" placeholder="请选择目的地" />
        </a-form-model-item>
        <!-- 用车事由 -->
        <a-form-model-item label="用车事由" prop="reason">
          <a-textarea v-model="form.reason" placeholder="请输入用车事由" :rows="4" />
        </a-form-model-item>

        <a-form-model-item :wrapper-col="{ span: 16, offset: 4 }">
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            提交
          </a-button>
          <a-button style="margin-left: 10px" @click="handleReset">
            重置
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
  </div>
</template>

<script>
  import moment from 'moment'

  import {
    apiPersonGetById,
    apiDepartmentList,
    apiVehicleApplicationCreate,
    apiPersonGetAllList,
    apiPersonGetAllListTree,
  } from '@/api/featch'

  import area from '@/assets/json/area.json'

  const personInfo = JSON.parse(window.sessionStorage.getItem('person_info') || '{}')

  export default {
    name: 'add-vehicle-application',
    data() {
      return {
        personInfo,
        // 表单数据
        form: {
          // 申请人id
          applicant_id: null,
          // 申请部门id
          department_id: null,
          // 申请时间
          apply_time: null,
          // 出发日期
          departure_date: null,
          // 出发时间段
          departure_time_period: '上午',
          // 返回日期
          return_date: null,
          // 返回时间段
          return_time_period: '上午',
          // 目的地
          destination: null,
          // 申请原因
          reason: null,
          // 乘车人id
          passenger_ids: []
        },
        // 部门列表
        departmentList: [],
        // 地区数据
        area: area.options,

        // 表单验证规则
        rules: {
          passenger_ids: [{
            required: true,
            message: '请选择乘车人',
            trigger: 'change'
          }],
          departure_date: [{
            required: true,
            message: '请选择出发日期',
            trigger: 'change'
          }],
          return_date: [{
            required: true,
            message: '请选择返回日期',
            trigger: 'change'
          }],
          destination: [{
            required: true,
            message: '请选择目的地',
            trigger: 'change'
          }],
          reason: [{
            required: true,
            message: '请输入用车事由',
            trigger: 'change'
          }]
        },

        // 人员列表
        personList1: [],
        personListTree1: [],
        personLoading: false,
        // 提交状态
        submitting: false
      }
    },
    mounted() {
      this.handleGetDataBefore()
      this.getInitialPersonListTree()
    },
    methods: {
      /**
       * @description 获取人员id 和 部门id
       */
      handleGetDataBefore() {
        // 申请人id
        this.form.applicant_id = this.personInfo.person_id

        apiPersonGetById({
            person_id: this.form.applicant_id
          })
          .then(res => {
            if (res.code === 200) {
              this.form.department_id = res.data.department_id
            }
          })

        apiDepartmentList()
          .then(res => {
            if (res.code === 200) {
              this.departmentList = res.data
            }
          })
      },
      /**
       * @description 获取初始人员列表
       */
      async getInitialPersonList() {
        this.personLoading = true
        try {
          const res = await apiPersonGetAllList({})
          if (res.code === 200) {
            this.personList1 = [...res.data]
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      /**
       * @description 获取初始人员列表 树状
       */
      async getInitialPersonListTree() {
        this.personLoading = true
        try {
          const res = await apiPersonGetAllListTree({})
          if (res.code === 200) {
            console.log(res.data)
            this.personListTree1 = [...res.data]
          } else {
            this.$message.error(res.message)
          }
        } catch (err) {
          this.$message.error(err.toString())
        }
        this.personLoading = false
      },
      /**
       * @description 提交表单
       */
      async handleSubmit() {
        this.$refs.form.validate(async valid => {
          if (valid) {
            this.submitting = true
            try {
              const res = await apiVehicleApplicationCreate({
                ...this.form,
                departure_date: moment(this.form.departure_date).format('YYYY-MM-DD'),
                return_date: moment(this.form.return_date).format('YYYY-MM-DD'),
                apply_time: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
                destination: this.form.destination.join("/")
              })
              if (res.code === 200) {
                this.$message.success('申请成功')
                this.$confirm({
                  title: '提示',
                  content: '申请提交成功，是否返回列表页？',
                  okText: '返回列表',
                  cancelText: '继续申请',
                  onOk: () => {
                    this.$router.push('/ov-main/vehicle-application')
                  },
                  onCancel: () => {
                    this.handleReset()
                  }
                })
              } else {
                this.$message.error(res.message)
              }
            } catch (err) {
              this.$message.error(err.toString())
            }
            this.submitting = false
          }
        })
      },

      /**
       * @description 重置表单
       */
      handleReset() {
        this.form = {
          // 申请人id
          applicant_id: null,
          // 申请部门id
          department_id: null,
          // 申请时间
          apply_time: null,
          // 出发日期
          departure_date: null,
          // 出发时间段
          departure_time_period: '上午',
          // 返回日期
          return_date: null,
          // 返回时间段
          return_time_period: '上午',
          // 目的地
          destination: null,
          // 申请原因
          reason: null,
          // 乘车人id
          passenger_ids: []
        }
        this.handleGetDataBefore()
      }
    }
  }
</script>

<style lang="less" scoped>
  .add-vehicle-application {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 24px;

    .header {
      margin-bottom: 12px;
      text-align: center;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .content {
      width: 100%;
      max-width: 800px;
      background: #fff;
      padding: 24px;
      border-radius: 4px;
      // box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
    }
  }
</style>